<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <link href="../css/mems-index.css" type="text/css" rel="stylesheet"/>
    <link rel="stylesheet" href="../css/user-manage.css">
</head>
<body>


<!--header-->
<header id="header" class="header">
    <div class="header-info left"><i></i><a href="user-manage.html">系统配置</a>&nbsp;>&nbsp;用户管理</div>
    <div class="right-user right">
        <div class="clear t" >
            <div id="headusername" class="role"></div>
            <div class="icon"></div>
        </div>
        <div class="head-down">
            <ul><li><a href="edit-pwd.html">修改密码</a></li><li><a onclick="loginOut()">退出系统</a></li></ul></div><div>
    </div>
    </div>
</header>
<!--menu-->
<aside id="aside" class="aside">
    <div class="logo">运营平台</div>
    <ul class="menu" id="asidemenu">
    </ul>
</aside>


<!--content-->
<div class="content">
    <div class="page-inner">
        <div class="item-header">
            <div class="search-box">
                <form action="javascript:;" id="search-user-form">
                    <input type="text" placeholder="姓名" id="userName-text">
                    <div class="search-icon" id="search-icon"></div>
                    <div class="search-input-border"></div>
                </form>
            </div>
            <div class="item-right">
                <button class="add-user-btn">添加用户</button>
            </div>
        </div>
        <div class="item-content">
            <div class="table-box">
                <table>
                    <thead>
                        <tr class="">
                            <th>姓名</th>
                            <th>用户名</th>
                            <th>电话</th>
                            <th>邮箱</th>
                            <th>角色</th>
                            <th>组织架构</th>
                            <th>岗位</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="bodyList">

                    </tbody>
                </table>
            </div>
            <div class="pages clear">
                <div class="page-list clear" id="pageList">

                </div>
            </div>
        </div>
    </div>
    <div class="add-user-box">
        <div class="add-user-back">
            <div class="add-user-form">
                <div>
                    <div class="form-name">姓名</div>
                    <div class="form-input">
                        <input type="text" name="name" id="name">
                    </div>
                </div>
                <div class="user-hidden">
                    <div class="form-name">用户名</div>
                    <div class="form-input">
                        <input type="text" name="userName" id="userName" >
                    </div>
                </div>
                <div>
                    <div class="form-name">组织架构</div>
                    <div class="form-input">
                        <input type="text" id="Dpt-select" name="department" id="department" readonly >
                    </div>
                </div>
                <div>
                    <div class="organize-content tree-content">

                    </div>
                </div>
                <div>
                    <div class="form-name">岗位</div>
                    <div class="form-input">
                        <select name="occupation"  id="occupation">
                        </select>
                    </div>
                </div>
                <div>
                    <div class="form-name">角色</div>
                    <div class="form-input">
                        <select name="role"  id="role">
                            <!--<option value="9">-->
                                <!--超级管理员-->
                            <!--</option>-->
                            <option value="0">
                                产品经理
                            </option>
                            <option value="1">
                                区域负责人
                            </option>
                            <option value="2">
                                普通用户
                            </option>
                            <option value="3">
                                全域管理员
                            </option>
                        </select>
                    </div>
                </div>
                <div>
                    <div class="form-name">电话</div>
                    <div class="form-input">
                        <input type="text" name="phone" id="phone">
                    </div>
                </div>
                <div>
                    <div class="form-name">邮箱</div>
                    <div class="form-input">
                        <input type="text" name="email" id="email">
                    </div>
                </div>
            </div>
        </div>
        <div class="user-btn-box">
            <button class="add-btn user-btn" id="add-btn">
                添加
            </button>
            <button class="cancel-user-btn user-btn">取消</button>
        </div>
    </div>
</div>
<div class="user-mask"></div>
<script src="../js/jquery.min.js"></script>
<script src="../js/jquery.cookie.js"></script>
<script src="../js/common.js"></script>
<script src="../js/user-tree.js"></script>
<script type="text/javascript">
    //角色限制
    var roleid = $.cookie('userrole');
    if(roleid == 0 || roleid ==2){
        alert('您无权查看！');
        location.href= 'mems-pro-list.html';
    }

    var userName= $('#userName-text').val();
    function getData(p,checPara){
        var PerPage = 10;
        var url  = _ip+'/user/getUserList?page='+p+'&size='+PerPage;
        var data = checPara || {'name': 'a'};
        $('#bodyList').html('');

        organizeAjaxPost(url, data, function(json) {
            if(!json.data || json.data.length <= 0){
                $('#bodyList').html('<tr><td colspan="8" style="text-align: center">暂无数据！</td></tr>');
                $('#pageList').html('');
                return false;
            }
            var _pager    = [];
            var _data = [];
            var userName= $('#userName-text').val();
            var totalPage = json.totlePage;
            var prev      = p-1;
            if(prev < 1)prev = 1;
            var next = p + 1;
            if(next > totalPage)next = totalPage;
            for(var k = 0, kk = json.data.length; k < kk; k++){
                var msg = json.data[k];
                var roleName = '-';
                var msgData = {
                    id: msg.id,
                    name: msg.name,
                    phone: msg.phone,
                    email: msg.email,
                    role: msg.role,
                    department: msg.department,
                    dptName: msg.dptName,
                    occupation: msg.occupation,
                    ocpName: msg.ocpName,
                    userName: msg.userName
                };
                switch (msgData.role) {
                    case 0:
                        roleName = '产品经理';
                        break;
                    case 1:
                        roleName = '区域负责人';
                        break;
                    case 2:
                        roleName = '普通用户';
                        break;
                    case 3:
                        roleName = '全域管理员';
                        break;
//                    case 9:
//                        roleName = '超级管理员';
//                        break;
                }
                _data[k] = $('<tr>' +
                        '<td>'+msg.name+'</td>' +
                        '<td>'+(msg.userName || "-")+'</td>' +
                        '<td>'+msg.phone+'</td>' +
                        '<td>'+ msg.email  +'</td>' +
                        '<td>'+roleName+'</td>' +
                        '<td>'+msg.dptName+'</td>' +
                        '<td>'+msg.ocpName+'</td>' +
                        '<td>' +
                        '<a href="javascript:;" onclick="editUser(this)">编辑</a>' +
                        '<a href="javascript:;" onclick="disableUser(this)" data-id="'+ msg.id +'">'+ (msg.status? "禁用":"启用") +'</a> ' +
                        '<a href="javascript:;" onclick="resetPwd(this)" data-id="'+ msg.id +'">重置密码</a>' +
                        '</td>' +
                        '</tr>');
                var $tr = _data[k].data('edit', msgData);
                $('#bodyList').append($tr).data('page', p);
            }
            _pager.push('<span>共：'+ totalPage +'页</span>');
            _pager.push('<span>您正在第：'+p+'页</span>');
            _pager.push('<a href="javascript:;" class="page-pre" onclick="pageClick('+prev+ ');return !1;">上一页</a>');
            _pager.push('<a href="javascript:;" class="page-next" onclick="pageClick('+next+');return !1;">下一页</a>');
            _pager.push('<span>前往第</span>');
            _pager.push('<input type="text" id="goToPage"/>');
            _pager.push('<span>页</span>');
            _pager.push('<button id="goToPageBtn">GO</button>');
            $('#pageList').html(_pager.join(""));
            $('#goToPageBtn').on('click',function () {
                var v = $('#goToPage').val();
                if(!/^[1-9]\d*$/.test(v)){
                    return false;
                }
                if(v>1 && v<totalPage){
                    getData(v, {name: userName});
                }
                if(v <= 1){
                    getData(1, {name: userName});
                    return false;
                }
                if(v >= totalPage){
                    getData(totalPage, {name: userName});
                    return false;
                }
            })



            $('#goToPage').bind('blur', function(event) {
                var userName= $('#userName-text').val();
                var v = parseInt($(this).val());
                if(!/^[1-9]\d*$/.test(v)){
                    return false;
                }else{
                    if(v <= 1){
                        getData(1, {name: userName});
                    }
                    else if(v >= totalPage){
                        getData(totalPage, {name: userName});
                    }else{
                        getData(v, {name: userName});
                    }
                }
            });
        });
    }
    getData(1, {name: userName});
    $('.cancel-user-btn, .user-mask').on('click', function() {
        var $addUserBox = $('.add-user-box');
        $('.add-user-back').find('input').val('').end().find('select option:selected').prop('selected', false);
        $('.user-mask').css('display', 'none');
        $addUserBox.find('[name="id"]').remove();
        $addUserBox.find('input,select').removeClass('error-i');
        $('.error-msg').remove();
        $addUserBox.animate({
            right: '-25%',
            opacity: 0
        }, 500);
    });
    $('.add-user-btn').on('click', function() {
        var $addUserBox = $('.add-user-box').data('edit', {});
        $('.organize-content').html('');
        $('.success-msg').remove();
        $('.user-mask').css('display', 'block');
        $addUserBox.find('[name="id"]').remove();
        $addUserBox.find('#add-btn').text('添加').removeClass('edit');
        $addUserBox.animate({
            right: '0px',
            opacity: 1
        }, 500);
    });

    $('#userName').on('blur', function() {
        verify_user($(this));
    });

    $('#Dpt-select').on('click', function() {
        var $obj = $(this);
        var id = $obj.data('id');
        getFirstOrganize(1, {}, $('.organize-content'));
    });

    $('#search-user-form').on('submit', function() {
        var userName= $('#userName-text').val();
        getData(1, {name: userName});
        return false;
    });

    $('#search-icon').on('click', function() {
        $('#search-user-form').submit();
    });

    $('#add-btn').on('click', function() {
        var $obj = $(this);
        var $userName = $('#userName');
        var emailFormat = /^[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?$/;
        var phoneFormat = /^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8]))\d{8}$/;
        var nameFormat = /^[\u4e00-\u9fa5]{2,}$/;
        var data = {
            name: $('#name').val(),
            userName: $userName.val(),
            department: $('#Dpt-select').data('id'),
            occupation: $('#occupation').val(),
            role: $('#role').val(),
            phone: $('#phone').val(),
            email: $('#email').val()
        };
        $('input, select').removeClass('error-i');
        $('.form-input').find('.error-msg').remove();
        $('.organize-content').html('');
        for (var key in data) {
            var $formLine = $('[name='+ key +']');
            if(data[key] === '') {
                $formLine.addClass('error-i');
                $formLine.parent().append('<p class="error-msg">'+
                        $formLine.closest('.form-input').prev().text()
                        +'不能为空</p>');
                return false;
            }
            else {
                if (key === 'name') {
                    var nameValidate = nameFormat.test(data[key]);
                    if (!nameValidate) {
                        if (data[key].length < 2 ) {
                            $formLine.addClass('error-i');
                            $formLine.parent().append('<p class="error-msg">'+
                                    $formLine.closest('.form-input').prev().text()
                                    +'长度必须大于2个字</p>');
                            return false;
                        }
                        $formLine.addClass('error-i');
                        $formLine.parent().append('<p class="error-msg">'+
                                $formLine.closest('.form-input').prev().text()
                                +'请输入中文</p>');
                        return false;
                    }
                }
                if (key === 'email') {
                    var emailValidate = emailFormat.test(data[key]);
                    if (!emailValidate) {
                        $formLine.addClass('error-i');
                        $formLine.parent().append('<p class="error-msg">'+
                               $formLine.closest('.form-input').prev().text()
                               +'格式错误</p>');
                        return false;
                    }

                }
                if (key === 'phone') {
                    var phoneValidate = phoneFormat.test(data[key]);
                    if (!phoneValidate) {
                        $formLine.addClass('error-i');
                        $formLine.parent().append('<p class="error-msg">'+
                                $formLine.closest('.form-input').prev().text()
                                +'格式错误</p>');
                        return false;
                    }

                }
            }
        }
        var url  = _ip+'/user/insertUser';
        if ($obj.hasClass('edit')) {
            url  = _ip+'/user/updateUser';
            data.id = $('[name="id"]').val();
        }
        verify_user($userName, function() {
            organizeAjaxPost(url, data, function(json) {
                if (json.success) {
                    $('.cancel-user-btn').click();
                    getData(1, {name: userName});
                }
            });
        });
    });

    function verify_user($obj, callback) {
        var userName = $obj.val();
        var url  = _ip+'/user/verify';
        var data = {
            userName: userName
        };
        var $addUserBox = $obj.closest('.add-user-box');
        var dataUserName = $addUserBox.data('edit').userName;
        $('.error-msg').remove();
        $('.success-msg').remove();
        if (data.userName && data.userName === dataUserName) {
            if(callback) {
                callback();
            }
            return false;
        }
        organizeAjaxGet(url, data, 'verifyUser', function(json) {
            if (json.success) {
                $obj.parent().append('<p class="success-msg">'+ json.message +'</p>');
                if(callback) {
                    callback();
                }
            }
            else {
                $obj.parent().append('<p class="error-msg">'+ json.message +'</p>');
            }
        })
    }

    function pageClick(page) {
        var userName= $('#userName-text').val();
        getData(page, {name: userName});
    }

    function editUser(obj) {
        var data = $(obj).closest('tr').data('edit');
        var $addUserBox = $('.add-user-box');
        $('.success-msg').remove();
        $addUserBox.append('<input type="hidden" name="id"/>').data('edit', data);
        for (var key in data) {
            $('[name="' + key + '"]').val(data[key]);
        }
        $addUserBox.find('#Dpt-select').val(data.dptName).data('id', data.department);
        getQuartersSelect(data.occupation);
        $addUserBox.find('#add-btn').text('编辑').addClass('edit');
        $('.user-mask').css('display', 'block');
        $addUserBox.animate({
            right: '0px',
            opacity: 1
        }, 500);
    }

    function disableUser(obj) {
        var data = {};
        var id =  $(obj).data('id');
        var url  = _ip+'/user/disableUser';
        data.id = id;
        if(!id) {
            return false;
        }
        organizeAjaxGet(url, data, 'disableUser', function(json) {
            if (json.success) {
                successAlert('您已成功'+ $(obj).text()  +'用户！');
                getData($('#bodyList').data('page'), {name: userName});
            }
        })
    }

    function resetPwd(obj) {
        if(globleRoleId != 9){
            alert('您无权重置密码！');
            return;
        }
        var data = {};
        var id =  $(obj).data('id');
        var url  = _ip+'/user/resetPwd';
        data.id = id;
        if(!id) {
            return false;
        }
        organizeAjaxGet(url, data, 'resetPwd', function(json) {
            if (json.success) {
                successAlert('您已成功将密码重置为默认密码！');
            }
        })
    }

    function treeTitleClick(obj) {
        var $obj = $(obj);
        var $li = $obj.closest('li');
        var id = $li.attr('id');
        var text = $li.find('>.tree-title .tree-text').text();
        $('#Dpt-select').val(text).data('id', id);
        $('.organize-content').html('');
        getQuartersSelect();
    }

    function getQuartersSelect(defaultId) {
        var id = $('#Dpt-select').data('id');
        var url  = _ip+'/ocp';
        var data = {
            dpt: id
        };
        organizeAjaxGet(url, data, 'getQuarters_select', function(json) {
            if (json.success) {
                var h = '';
                var data = json.data;
                h += '<option value="">请选择</option>';
                for(var k = 0 , kk = data.length; k < kk; k++){
                    h += '<option value="'+data[k].id+'" '+  (data[k].id == defaultId?"selected":""  ) +'>'+data[k].occupation+'</option>';
                }
                $('#occupation').html(h);
            }
        });
    }

</script>
</body>
</html>